import axios from 'axios'
import qs from 'qs'
import router from '@/router'
import tipMessage from "@/utils/tipMessage"
import store from '../store/index.js'
import {solarPowerSystem } from '@/common/projectAlias'
import { CommonResponse } from '../interface/xhr.js'
import { PlainObject } from '../interface/base.js'
/**
 * 提示函数
 */
const tip = (msg:string) => {
    tipMessage(msg, 'error');
};

/**
 * 请求失败后的错误统一处理
 * @param status 请求失败的状态码,这块还没设置
 * @param msg 接口失败返回的说明
 */
const errorHandle = (status:string | number | null, msg:string) => {
    switch (status) {
        case 500:
            tip(msg || '服务错误');
            break;
        case 502:
            tip(msg || '接口缺失，请联系管理员');
            break;
        case 401:
            tip('登录超时，请重新登录！');
            sessionStorage.removeItem('upmSessionId');
            router.push('/login');
            break;
        case 404:
            tip(msg || '找不到接口，请联系管理员！');
            break;
        case 421:
            tip('登录超时，请重新登录！');
            sessionStorage.removeItem('upmSessionId');
            router.push('/login');
            break;
        case "421":
            tip('登录超时，请重新登录！');
            sessionStorage.removeItem('upmSessionId');
            router.push('/login');
            break;
        default:
            tip(msg || '未知错误');
            break;
    }
};

/**
 * 将外部的状态码进行一个处理
 * @param msg   外部服务器错误的一个信息
 */
const dealCode = (msg: string) => {
    let code = null;
    if (msg.indexOf('404')>-1) code = 404;
    if (msg.indexOf('500')>-1) code = 500;
    if (msg.indexOf('502')>-1) code = 502;
    return code
}

/**
 * axios基础设置
 * @type {number}
 */
axios.defaults.timeout = 15000;

//创建axios实例
const instance = axios.create({});

/**
 * 请求拦截
 */
instance.interceptors.request.use(
    (config) => {
        config.headers["X-TBD-TOKEN"] = sessionStorage.upmSessionId || '';
        //菜单code
        config.headers["menuCode"] = router.currentRoute.value?.meta?.menuCode??'';
        //应用别名
        config.headers["projectAlias"] = solarPowerSystem;
        return config
    },
    (error) => {
        return Promise.reject(error)
    }
)

/**
 * 响应拦截
 */
instance.interceptors.response.use(
    (response ) => {
        //内部  请求 || 导出
        // console.log('response',response);
        if (response.status === 200 && response.data.success || response.status === 200 && response.data.type || response.status === 200 && response.data.status === 'success') {
            let result = response.data; //本地文件的请求
            if (response.data.success) result = response.data;
            return Promise.resolve(result);
        } else {
            errorHandle(response.data.error_code, response.data.error_msg);
            return Promise.reject(response)
        }
    },
    (error) => {
        //外部
        let code:number | null = dealCode(error.message);
        errorHandle(code,error.message);
        return Promise.reject(error);
    }
)

// export default instance

const baseUrl = '/simulation/';
const loginUrl = '/config-center/';
const suanfaUrl = '/suanfa/'
const uploadUrl = '/uploadpic/'
export class Api {
    private baseUrl: string = '/simulation/'
    constructor(url: string){
        this.baseUrl = url
    }
    
    protected getFun<T extends CommonResponse>(url: string, config: PlainObject = {}): Promise<T> {
       return instance.get(this.baseUrl+url,{...config})
    }
    protected getQueryFun<T extends CommonResponse>(url: string, params: PlainObject = {}, config: PlainObject={}): Promise<T> {
        return instance.get(this.baseUrl + url + '?' + qs.stringify(params),{ ...config })
    }
    protected postFun<T extends CommonResponse>(url: string, config: PlainObject = {}): Promise<T> {
        return instance.post(this.baseUrl + url,{ ...config })
    }
    protected postBodyFun<T extends CommonResponse>(url: string, params: PlainObject = {}, config: PlainObject = {}): Promise<T> {
        return instance.post(this.baseUrl + url, params, { ...config })
    }
    protected getJson<T extends CommonResponse>(url: string) : Promise<T> {
        return instance.get(url)
    }
    protected downExcel<T extends CommonResponse>(url: string, params: null = null, config: PlainObject = {}): Promise<T> {
        return instance.post(this.baseUrl + url, params, { ...config, responseType: 'blob'})
    }
}
